package com.zlyx.easy.swagger.utils;

import static com.google.common.base.Optional.fromNullable;
import static com.google.common.base.Predicates.not;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.FluentIterable.from;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newHashMap;
import static springfox.documentation.schema.Types.typeNameFor;

import java.util.Map;

import com.google.common.base.Predicate;
import com.google.common.base.Strings;

import io.swagger.annotations.ResponseHeader;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.schema.ModelReference;
import springfox.documentation.service.Header;

/**
 * @Auth 赵光
 * @Describle
 * @2019年6月27日 下午8:13:39
 */
public class ResponseUtils {

	public static Map<String, Header> getHeaders(ResponseHeader[] responseHeaders) {
		Map<String, Header> headers = newHashMap();
		for (ResponseHeader each : from(newArrayList(responseHeaders)).filter(not(emptyOrVoid()))) {
			headers.put(each.name(), new Header(each.name(), each.description(), headerModel(each)));
		}
		return headers;
	}

	protected static Predicate<ResponseHeader> emptyOrVoid() {
		return new Predicate<ResponseHeader>() {
			@Override
			public boolean apply(ResponseHeader input) {
				return Strings.isNullOrEmpty(input.name()) || Void.class.equals(input.response());
			}
		};
	}

	protected static ModelReference headerModel(ResponseHeader each) {
		ModelReference modelReference;
		String typeName = fromNullable(typeNameFor(each.response())).or("string");
		if (isNullOrEmpty(each.responseContainer())) {
			modelReference = new ModelRef(typeName);
		} else {
			modelReference = new ModelRef(each.responseContainer(), new ModelRef(typeName));
		}
		return modelReference;
	}
}
